package com.yulebaby.callsenter.ui.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.fourmob.datetimepicker.date.DatePickerDialog;
import com.yulebaby.callsenter.R;
import com.yulebaby.callsenter.adapter.TrackStepAdapter;
import com.yulebaby.callsenter.bean.CallLogBean;
import com.yulebaby.callsenter.bean.CustomerBean;
import com.yulebaby.callsenter.bean.PreSaleRemarkBean;
import com.yulebaby.callsenter.bean.ResultBean;
import com.yulebaby.callsenter.bean.TrackStepBean;
import com.yulebaby.callsenter.event.EventFactory;
import com.yulebaby.callsenter.event.QuitEvent;
import com.yulebaby.callsenter.event.RefreshEvent;
import com.yulebaby.callsenter.global.Constant;
import com.yulebaby.callsenter.http.HttpHelper;
import com.yulebaby.callsenter.http.callback.HttpCallback;
import com.yulebaby.callsenter.task.UploadPreSaleRemarkTask;
import com.yulebaby.callsenter.ui.base.BaseActivity;
import com.yulebaby.callsenter.ui.view.PickerDialog;
import com.yulebaby.callsenter.ui.view.RecycleDivider;
import com.yulebaby.callsenter.ui.view.YuLeBaByFlowLayout;
import com.yulebaby.callsenter.ui.view.YuLeBaByLinearLayoutManager;
import com.yulebaby.callsenter.utils.CommonUtil;
import com.yulebaby.callsenter.utils.DateUtil;
import com.yulebaby.callsenter.utils.KeyBoardUtils;
import com.yulebaby.callsenter.utils.ThreadUtils;
import com.yulebaby.callsenter.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;

import static com.yulebaby.callsenter.global.Constant.CUSTOMER_BEAN;


public class AddPreSaleRemarkActivity extends BaseActivity implements DatePickerDialog.OnDateSetListener, View.OnClickListener {

    /**
     * 客户ID
     */
    private static final int UPLOADFILE = 1;


    private CustomerBean customerbean;
    private ImageView mIv_searchback;
    private View mLayout_trackcount, mLayout_trackmode, mLayout_trackbody, mLayout_progress, mLayout_remark;
    private PickerDialog mCommunicationDialog;
    private TextView mTvCommunication, mNextVisitTime, mTv_save;
    private EditText mEtTrackBody;
    public static final String YULEBABY_TAG = "yulebaby";
    final Calendar calendar = Calendar.getInstance();
    final DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), true);
    private YuLeBaByFlowLayout flowlayout;
    private TextView mTextview;
    private ViewGroup.MarginLayoutParams lp;
    private ArrayList<TextView> tvList;
    // 定义文字的间距
    private int hPadding, vPadding;
    private StringBuffer sb;
    private String[] mStr;

    private HashSet<TrackStepBean> seletedItem = new HashSet<>();

    private ArrayList<String> mPicUrl;
    private ArrayList<CallLogBean> mSelectCallList;
    private TrackStepBean clickBean;
    private View mHeard;
    private RecyclerView mRvTrackRemark;
    private TrackStepAdapter mTrackStepAdapter;

    private void bindViews() {
        mRvTrackRemark = (RecyclerView) findViewById(R.id.rv_trackremark);
        mHeard = LayoutInflater.from(this).inflate(R.layout.layout_addtrack_head, null);

        initRecycleView();

        mIv_searchback = (ImageView) findViewById(R.id.iv_searchback);
        mTv_save = (TextView) findViewById(R.id.tv_save);

        mLayout_trackcount = mHeard.findViewById(R.id.layout_trackcount);
        mLayout_trackmode = mHeard.findViewById(R.id.layout_trackmode);
        mLayout_trackbody = mHeard.findViewById(R.id.layout_trackbody);
        mLayout_progress = mHeard.findViewById(R.id.layout_progress);
        flowlayout = (YuLeBaByFlowLayout) mHeard.findViewById(R.id.flowlayout);

        mLayout_trackmode.setClickable(true);
        mLayout_progress.setClickable(true);
        mLayout_trackmode.setOnClickListener(this);
        mLayout_progress.setOnClickListener(this);
        mIv_searchback.setOnClickListener(this);
        mTv_save.setOnClickListener(this);
    }

    private void initRecycleView() {
        List<TrackStepBean> stepList = TrackStepBean.getStepList();
        for (int i = 1; i <= customerbean.getTrack_pro(); i++) {
            stepList.get(i).setIsSelected(2);
        }
        stepList.remove(0);
        mTrackStepAdapter = new TrackStepAdapter(stepList);
        mTrackStepAdapter.addHeaderView(mHeard);
        mRvTrackRemark.setHasFixedSize(true);
        mRvTrackRemark.setLayoutManager(new YuLeBaByLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        mRvTrackRemark.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                TrackStepBean bean = (TrackStepBean) baseQuickAdapter.getItem(i);
                if (bean.getIsSelected() == 1 && bean.getTrackNum() <= 3) {
                    bean.setIsSelected(0);
                    baseQuickAdapter.notifyDataSetChanged();
                    seletedItem.remove(clickBean); //理论相同
                } else if (bean.getIsSelected() == 1 && bean.getTrackNum() > 3) {
                    if (seletedItem.size() > 0 && seletedItem.iterator().next() == bean) {
                        Intent intent = new Intent(AddPreSaleRemarkActivity.this, UploadFileActivity.class);
                        intent.putExtra(Constant.SELECED_PIC, mPicUrl);
                        intent.putExtra(Constant.SELECED_RECORD, mSelectCallList);
                        startActivityForResult(intent, UPLOADFILE);
                    } else {
                        ToastUtil.showToast("跟踪进展不可多选哦^_^");
                    }
                } else if (seletedItem.size() != 1 && bean.getIsSelected() != 2) {
                    if (bean.getTrackNum() > 3) {
                        Intent intent = new Intent(AddPreSaleRemarkActivity.this, UploadFileActivity.class);
                        intent.putExtra(Constant.SELECED_PIC, mPicUrl);
                        intent.putExtra(Constant.SELECED_RECORD, mSelectCallList);
                        startActivityForResult(intent, UPLOADFILE);
                    } else if (bean.getTrackNum() <= 3) {
                        seletedItem.add(bean);
                        bean.setIsSelected(1);
                        baseQuickAdapter.notifyDataSetChanged();
                    } else {
                        ToastUtil.showToast("跟踪进展不可多选哦^_^");
                    }
                    clickBean = bean;
                } else if (bean.getIsSelected() == 2) {

                } else {
                    ToastUtil.showToast("跟踪进展不可多选哦^_^");
                }
            }
        });
        mRvTrackRemark.addItemDecoration(new RecycleDivider(this, RecycleDivider.VERTICAL_LIST));
        mRvTrackRemark.setAdapter(mTrackStepAdapter);
    }

    @Override
    protected int initLayoutId() {
        return R.layout.activity_add_pre_sale_remark;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        bindViews();
        initScentMarchData();
        tvList = new ArrayList<>();
        ((TextView) mLayout_trackcount.findViewById(R.id.tv_left)).setText("售前跟踪次数");

        ((TextView) mLayout_trackcount.findViewById(R.id.tv_right)).setText(String.valueOf(customerbean.getVisit_times() + 1));
        ((TextView) mLayout_trackmode.findViewById(R.id.tv_left)).setText("跟踪方式");
        mTvCommunication = (TextView) mLayout_trackmode.findViewById(R.id.tv_right);

        mTvCommunication.setText("电话");
        mLayout_trackmode.findViewById(R.id.iv_canselect).setVisibility(View.VISIBLE);

        mEtTrackBody = (EditText) mLayout_trackbody.findViewById(R.id.et_bottom);
        mEtTrackBody.setEnabled(true);
        editTextRequestFocus(mEtTrackBody);

        ((TextView) mLayout_progress.findViewById(R.id.tv_left)).setText("下次跟踪时间");
        mNextVisitTime = (TextView) mLayout_progress.findViewById(R.id.tv_right);
        mLayout_progress.findViewById(R.id.iv_canselect).setVisibility(View.VISIBLE);
        mNextVisitTime.setText(DateUtil.getNextDate());
        initDialog();

    }

    /**
     * 返回结果
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case UPLOADFILE:
                if (resultCode == RESULT_OK && data != null) {
                    mPicUrl.clear();
                    mSelectCallList.clear();
                    ArrayList<String> picUrl = (ArrayList<String>) data.getSerializableExtra(Constant.SELECED_PIC);
                    ArrayList<CallLogBean> selectCallList = (ArrayList<CallLogBean>) data.getSerializableExtra(Constant.SELECED_RECORD);
                    if (picUrl != null) {
                        clickBean.setFileCount(picUrl.size());
                        mPicUrl.addAll(picUrl);
                    }
                    if (selectCallList != null) {
                        clickBean.setFileCount(clickBean.getFileCount() + selectCallList.size());
                        mSelectCallList.addAll(selectCallList);
                    }
                    if (clickBean.getFileCount() != 0) {
                        clickBean.setIsSelected(1);
                        seletedItem.add(clickBean);
                    } else {
                        seletedItem.remove(clickBean);
                        clickBean.setIsSelected(0);
                    }
                    mTrackStepAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    /**
     * 流式布局
     */
    private void initScentMarchData() {
        sb = new StringBuffer();
        // 得到当前文字的Padding值
        hPadding = CommonUtil.getDimens(R.dimen.space_17);
        vPadding = CommonUtil.getDimens(R.dimen.space_8);

        lp = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = 50;
        lp.rightMargin = 40;
        lp.topMargin = 64;
        lp.bottomMargin = 10;
        if (mStr != null) {
            ThreadUtils.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < mStr.length; i++) {
                        mTextview = new TextView(AddPreSaleRemarkActivity.this);
                        tvList.add(mTextview);
                        mTextview.setOnClickListener(AddPreSaleRemarkActivity.this);
                        mTextview.setTag(i);
                        mTextview.setText(mStr[i]);
                        mTextview.setTextColor(0xff666666);
                        mTextview.setTextSize(15);
                        mTextview.setBackground(getResources().getDrawable(R.drawable.scent_text_selector));
                        // 设置当前的间距
                        mTextview.setPadding(hPadding, vPadding, hPadding, vPadding);
                        flowlayout.addView(mTextview,lp);

                    }
                }
            });
        }
        return;
    }

    /**
     * 初始化对话框
     */
    private void initDialog() {
        mCommunicationDialog = new PickerDialog(this);
        processContentResult(mTvCommunication, mCommunicationDialog);
    }

    /**
     * 对接口回调进行处理
     *
     * @param tv
     * @param dialog
     */
    private void processContentResult(TextView tv, PickerDialog dialog) {
        dialog.setCurrentContentListener(result -> tv.setText(result));
    }

    @Override
    protected void initData() {
        mPicUrl = new ArrayList<>();
        mSelectCallList = new ArrayList<>();
        mStr = CommonUtil.getStringArray(R.array.scent_content);
        Intent intent = getIntent();
        customerbean = (CustomerBean) intent.getSerializableExtra(CUSTOMER_BEAN);
    }

    /**
     * 日期选择
     */
    private void initDatePick() {
        datePickerDialog.setVibrate(true);
        datePickerDialog.setYearRange(2010, 2030);
        datePickerDialog.setCloseOnSingleTapDay(false);
        datePickerDialog.show(getSupportFragmentManager(), YULEBABY_TAG);
    }

    /**
     * Edittext获取焦点
     *
     * @param editText
     */
    private void editTextRequestFocus(EditText editText) {
        editText.setSelection(editText.getText().length());
        editText.getSelectionStart();
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
    }

    /**
     * 结果进行非空判断
     *
     * @param str
     * @return
     */
    private String checkNull(String str) {
        if (TextUtils.isEmpty(str)) {
            str = "";
        }
        return str;
    }

    @Override
    public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) {
        long visitTime = DateUtil.stringToLong(year + "-" + (month + 1) + "-" + day);
        long now = DateUtil.stringToLong(DateUtil.getCurrentDate());
        if (visitTime <= now) {
            ToastUtil.showToast("下次跟踪时间不能小于当前时间");
            mNextVisitTime.setText(DateUtil.getNextDate());
        } else {
            mNextVisitTime.setText(year + "-" + (month + 1) + "-" + day);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getTag() != null) {
            int tag = (int) v.getTag();
            if ("".equals(mEtTrackBody.getText().toString().trim())) {
                if (sb.length() > 0) {
                    sb.setLength(0);
                    sb.append(tvList.get(tag).getText());
                    mEtTrackBody.setText(sb);
                } else {
                    sb.append(tvList.get(tag).getText());
                    mEtTrackBody.setText(sb);
                }
            } else {
                sb.setLength(0);
                sb.append(mEtTrackBody.getText());
                sb.append(tvList.get(tag).getText());
                mEtTrackBody.setText(sb);
                mEtTrackBody.setSelection(sb.length());
            }
        }
        switch (v.getId()) {
            case R.id.layout_trackmode://跟踪方式
                showPickDialog(mCommunicationDialog, CommonUtil.getStringArray(R.array.picker_communication));
                break;
            case R.id.layout_progress://下次跟踪时间
                initDatePick();
                break;
            case R.id.iv_searchback:
                KeyBoardUtils.closeKeybord(this, mEtTrackBody);
                finish();
                break;
            case R.id.tv_save:
                saveRemark();
                break;
        }
    }

    /**
     * 保存跟踪记录
     */
    private void saveRemark() {

        if (KeyBoardUtils.getKeybordState(this)) {
            KeyBoardUtils.closeKeybord(this);
        }
        String way = mTvCommunication.getText().toString().trim();
        String time = mNextVisitTime.getText().toString().trim();
        String trackBody = mEtTrackBody.getText().toString().trim();

        if (TextUtils.isEmpty(way)) {
            ToastUtil.showToast("跟踪方式不能为空");
            return;
        }
        if (TextUtils.isEmpty(time)) {
            ToastUtil.showToast("下次跟踪时间不能为空");
            return;
        }
        if (TextUtils.isEmpty(trackBody)) {
            ToastUtil.showToast("跟踪内容不能为空");
            return;
        }
        long visitTime = DateUtil.stringToLong(time);
        if (visitTime != -1l) {
            ArrayList<String> recordPathlist = new ArrayList<>();
            for (CallLogBean logBean : mSelectCallList) {
                recordPathlist.add(logBean.getFile_path());
            }
            showLoading("正在上传请稍后");
            int trackNum = 0;
            if (seletedItem.size() > 0) {
                trackNum = seletedItem.iterator().next().getTrackNum();
            }
            UploadPreSaleRemarkTask.doUploadPreSaleRemark(this, new PreSaleRemarkBean(customerbean.getVisit_times(), trackBody,
                    way, customerbean.getCustomer_id(), visitTime, trackNum, recordPathlist, mPicUrl), new HttpCallback<ResultBean>() {
                public void onSuccessResultNull() {
                    super.onSuccessResultNull();
                    dismissLoading();
                    //跳转成功界面
                    Intent intent = new Intent(AddPreSaleRemarkActivity.this, SavePreSaleResultActivity.class);
                    intent.putExtra(CUSTOMER_BEAN, customerbean);
                    startActivity(intent);
                    EventBus.getDefault().post(EventFactory.CreateRefreshEvent(RefreshEvent.refreshDataFromInternet));
                    finish();
                }

                @Override
                public void onFailParam(String info) {
                    super.onFailParam(info);
                    dismissLoading();
                }

                @Override
                public void onFail(String exception) {
                    super.onFail(exception);
                    dismissLoading();
                    //跳转失败界面
                    Intent intent = new Intent(AddPreSaleRemarkActivity.this, SaveLoseActivity.class);
                    startActivity(intent);
                    finish();
                }
            });

        }
    }

    /**
     * 显示Dialog
     *
     * @param values
     */
    private void showPickDialog(PickerDialog dialog, String[] values) {
        if (KeyBoardUtils.getKeybordState(this)) {
            KeyBoardUtils.closeKeybord(this);
        }
        if (dialog == null) {
            dialog = new PickerDialog(this);
        }
        if (dialog.isShowing()) {
            dialog.dismiss();
        } else {
            dialog.setCancelable(true);
            dialog.setCanceledOnTouchOutside(true);
            dialog.show();
            dialog.initPicker(values);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        KeyBoardUtils.closeKeybord(this, mEtTrackBody);
    }

    /**
     * 接受退出的请求
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void quitEvent(QuitEvent event) {
        if (event != null) {
            HttpHelper.getInstance().cancel(this);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        dismissLoading();
    }
}
